package com.cpr.ams.service.impl;

import com.cpr.ams.bean.*;
import com.cpr.ams.bean.extend.BaseUserExtend;
import com.cpr.ams.bean.extend.Statistical;
import com.cpr.ams.exception.AmsException;
import com.cpr.ams.mapper.*;
import com.cpr.ams.mapper.extend.BaseRoleExtendMapper;
import com.cpr.ams.mapper.extend.BaseUserExtendMapper;
import com.cpr.ams.service.IBaseUserService;
import com.cpr.ams.util.StatusCode;
import com.cpr.ams.vm.UserVM;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 用户业务逻辑实现类
 * @Author: GX Cui
 * @Date 10:44 下午 2021/4/10
 * @Param
 * @Return
 */
@Service
public class BaseUserServiceImpl implements IBaseUserService {
    @Resource
    private BaseUserExtendMapper baseUserExtendMapper;
    @Resource
    private BaseUserMapper baseUserMapper;
    @Resource
    private BaseUserRoleMapper baseUserRoleMapper;
    @Resource
    private BaseRoleExtendMapper baseRoleExtendMapper;
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private PayServiceMapper payServiceMapper;
    @Resource
    private ServiceRecordMapper serviceRecordMapper;

    @Override
    public BaseUser login(UserVM userVM) throws AmsException {
        BaseUserExample example1 = new BaseUserExample();
        example1.createCriteria().andUserNameEqualTo(userVM.getUserName());
        List<BaseUser> list = baseUserMapper.selectByExample(example1);
        if(list.size()<=0){
            throw new AmsException(StatusCode.USER_NOT_EXIST);
        }
        BaseUser user = list.get(0);
        if(!user.getPassword().equals(userVM.getPassword())){
            throw new AmsException(StatusCode.USER_LOGIN_ERROR);
        }
        return user;
    }

    @Override
    public BaseUserExtend findById(int id) {
        return baseUserExtendMapper.selectById(id);
    }

    @Override
    public List<BaseUser> findAll() {
        return baseUserMapper.selectByExample(new BaseUserExample());
    }

    @Override
    public List<BaseUserExtend> cascadeRoleFindAll() {
        return baseUserExtendMapper.selectAll();
    }

    @Override
    public int saveOrUpdate(BaseUser baseUser) throws AmsException {
        int i = -100;
        if(baseUser.getId()!=null){
            baseUserMapper.updateByPrimaryKey(baseUser);
        } else {
            // 判断用户名是否被占用
            BaseUserExample example = new BaseUserExample();
            example.createCriteria().andUserNameEqualTo(baseUser.getUserName());
            List<BaseUser> list = baseUserMapper.selectByExample(example);
            if(list.size()>0){
                throw new AmsException(StatusCode.USER_HAS_EXISTED);
            }
            // 初始化
            baseUser.setRegisterTime(String.valueOf(new Date().getTime()));
            baseUser.setStatus(BaseUserExtend.STATUS_NORMAL);
            baseUserMapper.insertSelective(baseUser);
            i = baseUser.getId();
            //对新增用户赋予租户角色，后期可进行修改
            List<Integer> roles = new LinkedList<>();
            roles.add(2);
            setRoles(i,roles);
        }
        return i;
    }

    @Override
    public void changeStatus(int id, String status) throws AmsException {
        BaseUser user = this.findById(id);
        if(user==null){
            throw new AmsException(StatusCode.USER_NOT_EXIST);
        }
        user.setStatus(status);
        baseUserMapper.updateByPrimaryKey(user);
    }

    @Override
    public void deleteById(int id) throws AmsException {
        BaseUser user = this.findById(id);
        if(user==null){
            throw new AmsException(StatusCode.USER_NOT_EXIST);
        }
        baseUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void setRoles(int id, List<Integer> roles) {
        // 根据userid查询自己的角色
        BaseUserRoleExample example = new BaseUserRoleExample();
        example.createCriteria().andUserIdEqualTo(id);
        // 用户角色关系,获取所有老的角色
        List<BaseUserRole> list = baseUserRoleMapper.selectByExample(example);
        List<Integer> oldRoles = new ArrayList<>();
        Iterator<BaseUserRole> iterator = list.iterator();
        while(iterator.hasNext()){
            oldRoles.add(iterator.next().getRoleId());
        }
        // [1,2,3] -> [3,4] 添加1,2 => [1,2,3,4]
        // 依次判断新角色是否存在于list中，如果不存在则添加
        for(Integer roleId : roles){
            if(!oldRoles.contains(roleId)){
                BaseUserRole userRole = new BaseUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(id);
                baseUserRoleMapper.insert(userRole);
            }
        }
        // [1,2,3] -> [1,2,3,4]   删除 3,4  => [1,2]
        // 依次判断老的角色是否存在于roles中，如果不存在则删除
        for(BaseUserRole userRole : list){
            if(!roles.contains(userRole.getRoleId())){
                BaseUserRoleExample example1 = new BaseUserRoleExample();
                baseUserRoleMapper.deleteByPrimaryKey(userRole.getId());
            }
        }
    }

    @Override
    public List<BaseUser> findByRoleId(int roleId) {
        return baseUserExtendMapper.selectByRoleId(roleId);
    }

    @Override
    public Statistical getStatisticalData() {
        //新建对象
        Statistical statistical = new Statistical();
        //获取用户数量
        long userCount = baseUserMapper.countByExample(new BaseUserExample());
        //获取工单数量
        long workOrderCount = serviceRecordMapper.countByExample(new ServiceRecordExample());
        //获取订单数量
        long orderCount = payServiceMapper.countByExample(new PayServiceExample());
        //获取房间数量
        long roomCount = roomMapper.countByExample(new RoomExample());
        //封装
        statistical.setUserCount(userCount);
        statistical.setWorkOrderCount(workOrderCount);
        statistical.setOrderCount(orderCount);
        statistical.setRoomCount(roomCount);
        return statistical;
    }
}
